package com.bloom.opensourceframework.retrofit.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;

import com.bloom.opensourceframework.R;
import com.bloom.opensourceframework.activity.BaseActivity;
import com.bloom.opensourceframework.retrofit.adapter.GirlsAdapter;
import com.bloom.opensourceframework.retrofit.model.GirlBean;
import com.bloom.opensourceframework.retrofit.model.GirlEntity;
import com.bloom.opensourceframework.retrofit.remote.ApiUtils;
import com.bloom.opensourceframework.retrofit.remote.GirlService;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by bloom on 2018/5/7.
 */

public class RetrofitExampleActivity extends BaseActivity {

    private RecyclerView mRecyclerView;
    private GirlsAdapter mGirlsAdapter;
    private List<GirlEntity> mGirlsList;

    private GirlService mGirlService;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit);
        setTitle(R.string.retrofit_activity_name);
        initView();
        mGirlService = ApiUtils.getGrilService();
        loadGirls();
    }

    private void initView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.rcv_content);
        setupRecyclerView();
    }

    private void setupRecyclerView() {
        final StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,
                StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mGirlsList = new ArrayList<>();
        mGirlsAdapter = new GirlsAdapter(this, mGirlsList);
        mRecyclerView.setAdapter(mGirlsAdapter);
    }

    private void loadGirls() {
        mGirlService.getGirls(2).enqueue(new Callback<GirlBean>() {
            @Override
            public void onResponse(Call<GirlBean> call, Response<GirlBean> response) {
                if (response.isSuccessful()) {
                    updateGirls(response.body());
                } else {
                    Log.v("request data", "load girls respone but return fail!!");
                }
            }

            @Override
            public void onFailure(Call<GirlBean> call, Throwable t) {
                Log.v("request data", "load girls request fail!!");
            }
        });
    }

    private void updateGirls(GirlBean girlBean) {
        if (girlBean.getResults() != null) {
            mGirlsList.clear();
            mGirlsList.addAll(girlBean.getResults());
            mGirlsAdapter.notifyDataSetChanged();
        }
    }
}
